#include <iostream>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
const int default_port = 8080;
int main()
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        std::cout << "sock创建失败" << std::endl;
        exit(0);
    }
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(default_port);//这里要记得转网络
    int opt=1;
    setsockopt(fd,SOL_SOCKET,SO_REUSEADDR |SO_REUSEPORT,&opt,sizeof(opt));
    int n = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    if (n < 0)
    {
        std::cout << "bind失败:" <<strerror(errno)<< std::endl;
        exit(0);
    }
    n = listen(fd, 5);
    if (n < 0)
    {
        std::cout << "listen失败" << std::endl;
        exit(0);
    }
    while (true)
    {
        struct sockaddr_in accept_addr;
        socklen_t len = sizeof(accept_addr);
        std::cout << "准备accept" << std::endl;
        int sockfd = accept(fd, (struct sockaddr *)&accept_addr, &len); // 我们这里只做演示，接收完一个，返回后就关掉
        std::cout << "accept成功" << std::endl;
        if (sockfd < 0)
        {
            std::cout << "accept失败" << std::endl;
            exit(0);
        }
        char buffer[1024];
        int length = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (length < 0)
        {
            std::cout << "接收失败" << std::endl;
            exit(0);
        }
        buffer[length] = 0;
        printf("接收到[%s]request", buffer);
        char outbuffer[1024];
        const char *hello = "<h1>hello world</h1>";
        snprintf(outbuffer, sizeof(outbuffer), "HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s", strlen(hello), hello);
        send(sockfd, outbuffer, strlen(outbuffer), 0);
        close(sockfd);
    }
    close(fd);
}